#多线程学习

import threading
import time
import queue

exitFlag = 0

#继承threading.Thread类，改写run方法
class myThread (threading.Thread):
    def __init__(self, threadID, name, delay):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.delay = delay
    #run方法 为线程具体活动操作
    def run(self):
        print ("开始线程：" + self.name)
        process_data(self.name,self.delay)
        # print_time(self.name, self.delay, 5)
        print ("退出线程：" + self.name)

def print_time(threadName, delay, counter):
    while counter:
        if exitFlag:
            threadName.exit()
        time.sleep(delay)
        print ("%s: %s" % (threadName, time.ctime(time.time())))
        counter -= 1

def process_data(threadName, q):
    global x
    while not exitFlag:
        # queueLock.acquire()
        if not workQueue.empty():
            data = q.get()
            # queueLock.release()
            x = x - 1
            print ("%s processing %s" % (threadName, data))
        else:
            # queueLock.release()
            pass
        time.sleep(1)

def test_thread():

    # 创建新线程，指定线程名和参数
    thread1 = myThread(1, "Thread-1", 2)
    thread2 = myThread(2, "Thread-2", 1)

    # 开启线程，通过start方法去调用run方法
    thread1.start()   # 主线程main分出第一个子线程
    thread1.setName("线程-1")
    thread2.start()   # 主线程main分出第二个子线程
    # thread1.join()    # 第一个子线程运行完毕前主线程阻塞
    # thread2.join()    # 第二个子线程运行完毕前主线程阻塞
    if(thread1.is_alive()):
        print("线程"+thread1.getName()+"执行中")    
    print ("主线程退出")   #join方法使得子线程全部执行完毕后主线程才会执行该句

exitFlag = 0
threadList = ["Thread-1", "Thread-2", "Thread-3"]
nameList = ["One", "Two", "Three", "Four", "Five"]
queueLock = threading.Lock()
workQueue = queue.Queue(10)
threads = []
threadID = 1
global x
x = 6548

# 创建新线程
for tName in threadList:
    thread = myThread(threadID, tName, workQueue)
    thread.start()
    threads.append(thread)
    threadID += 1

# queueLock.acquire()
i = 0
for word in nameList:
    workQueue.put(word)
    i = i + 1
    print("第"+str(i)+"个数据放入")
# queueLock.release()

# 等待队列清空
while not workQueue.empty():
    pass
queueLock.acquire()
x = x + 3
print(x)
queueLock.release()
# 通知线程是时候退出
exitFlag = 1

# 等待所有线程完成
for t in threads:
    t.join()
# aa  = 1
# while(1):
    
#    time.sleep(2) 
#    print(aa)
#    aa = aa + 1

print ("退出主线程")

#  if __name__ == '__main__':
   
#  test_thread()
#  test_thread_queue()